﻿using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Data;
using CommonTools;
using shop.Model;
using System.Threading.Tasks;
using System.Net;

namespace shop.Bll
{

	/// <summary>  </summary>
  	public class RefundRegistBll : MyDocBaseBll<RefundRegist> 
  	{

		/// <summary> 单据类型, 每个单据唯一 </summary>
		public override string DocFlag => DocFlagEnum.RefundRegist;


        public override string SavePermission => "03.11.2";

        public override string ModifyPermission => "03.11.3";

        public override string DeletePermission => "03.11.4";

        public override string CheckPermission => "03.11.5";

        public override string PrintPermission => "";

        

        public override bool CheckDocument(RefundRegist doc, IUser user, out string err)
        {
            
            if (doc == null)
            {
                err = Model.CN.Msg_Dociswrong;
                return false;
            }
            if (doc.DocId ==0)
            {
                err = Model.CN.Msg_QueryBeforeModify;
                return false;
            }

            doc.IsChecked = 1;

            DB.FSql.Update<RefundRegist>()
                .SetSource(doc)
                .Set(a => a.IsChecked, doc.IsChecked)
                .ExecuteAffrows();

            err = "";
            return true;

        }


		public override bool UnCheckDocument(RefundRegist doc, IUser user, out string err)
        {
            if (doc == null)
            {
                err = Model.CN.Msg_Dociswrong;
                return false;
            }
            if (doc.DocId == 0)
            {
                err = Model.CN.Msg_QueryBeforeModify;
                return false;
            }

            doc.IsChecked = 0;

            DB.FSql.Update<RefundRegist>()
                .SetSource(doc)
                .Set(a => a.IsChecked, doc.IsChecked)
                .ExecuteAffrows();

            err = "";
            return true;

        }



        #region 查询方法: 按照 id,编号, 日期...


        public override IEnumerable<RefundRegist> Query(DateTime? begin, DateTime? end, string keyWord, QueryDateEnum dateEnum = QueryDateEnum.OccurDate, params string[] args)
        {

            var rst = DB.FSql.Select<RefundRegist>()
                .Where(WhereExp)
                .Where(a => a.Isdel == false)
                .WhereIf(!string.IsNullOrEmpty(keyWord), a => a.Number.Contains(keyWord) || a.src_tids.Contains(keyWord))
                .WhereIf(args.Length > 0 && !string.IsNullOrEmpty(args[0]), a => a.PreparedBy == args[0]);


            //日期条件
            //if (begin.HasValue && end.HasValue)
            //{
            //    switch (dateEnum)
            //    {
            //        case QueryDateEnum.PreparedDate:
            //            rst = rst.Where(a => a.PreparedDate >= begin && a.PreparedDate <= end);
            //            break;
                    //case QueryDateEnum.OccurDate:
                        rst = rst.Where(a => a.OccurDate >= begin && a.OccurDate <= end);
                        //break;
            //        default:
            //            rst = rst.Where(a => a.OccurDate >= begin && a.OccurDate <= end);
            //            break;
            //    }
            //}

            List<RefundRegist> list = rst.OrderByDescending(a => a.DocId).Take(50).ToList();    //最多50个

            if (list.Count == 0)
            {
                //如果没有放宽条件
                rst = DB.FSql.Select<RefundRegist>()
                    .Where(this.WhereExp)
                    .WhereIf(true, "\"Isdel\" = 0 ")
                    .WhereIf(!string.IsNullOrEmpty(keyWord), a => a.Number.Contains(keyWord) || a.src_tids.Contains(keyWord))
                    .WhereIf(args.Length > 0 && !string.IsNullOrEmpty(args[0]), a => a.PreparedBy == args[0]);


                list = rst.OrderByDescending(a => a.DocId).Take(50).ToList();    //最多50个
            }

            DateTime time = DB.FSql.GetTime();  //获取服务器时间作为单据的读取时间

            foreach (RefundRegist doc in list)
            {
                doc.ReadTime = time;
            }
            return list;

        }

        #endregion

        /// <summary> 创建单据 </summary>
        public override RefundRegist CreateDoc()
        {
            return new RefundRegist() { DocFlag = this.DocFlag };
        }





		/// <summary> 删除单据 </summary>
		public override bool Delete(RefundRegist doc, IUser user, out string err)
        {
            doc.Isdel = true;
            doc.IsdelDate = DateTime.Now;

            if( base.Delete(doc, user, out err))
            {
                //DB.FSql.Update<RefundRegistImage>()
                //    .Where(a => a.Isdel == false && a.DocId == doc.DocId)
                //    .Set(a => a.Isdel, true)
                //    .ExecuteAffrows();
                return true;
            }
            else
            {
                return false;
            }
        }


		/// <summary> 保存,修改 </summary>
        public override bool Save(RefundRegist doc, IUser user, out string err)
        {
            err = "";
            if (doc == null)
            {
				err = Model.CN.Msg_SystemError;  // "系统错误, 请联系管理员!";
                return false;
            }


            if (doc.OccurDate == null) doc.OccurDate = DateTime.Today;
            doc.PreparedDate = doc.OccurDate.ToDate();


            if (string.IsNullOrEmpty(doc.src_tids)  )
            {
                err += "原始单号不能为空!";
            }

            //else if (string.IsNullOrEmpty(doc.Shop))
            //{
            //    err += "店铺名称不能为空!";
            //}
            if (string.IsNullOrEmpty(doc.LogiNo))
            {
                err += "快递单号不能为空!";
            }
            else if (string.IsNullOrEmpty(doc.Stock))
            {
                err += "仓库不能为空!";
            }
            //else if (string.IsNullOrEmpty(doc.RefundFrom))
            //{
            //    err += "赔偿来源不能为空";
            //}

            // 其他检查
            //int i = 1;
            //foreach (var item in doc.Items)
            //{
            //    item.ItemId = i; //排序 
            //    string str = "";
            //    if (string.IsNullOrEmpty(item.Method) )
            //    {
            //        str +=  "核算方式不能为空!";
            //    }
            //    //else if ( item.OccurDate == null)
            //    //{
            //    //    str += "开票日期不能为空!";
            //    //}

            //    //追加到err;
            //    if (str != "")
            //        err += string.Format(Model.CN.Msg_itemError, i, str); // $"第{i}行: {str} \r\n;";


            //    i++;
            //}


            if (!string.IsNullOrEmpty(err   ))
            {
                return false;   
            }

            //默认值
            doc.Isdel = false;
            doc.Remarks ??= string.Empty;
            if (doc.Reason == null) doc.Reason = string.Empty;
            if (doc.Processor == null) doc.Processor = string.Empty;
            if (doc.spec_no== null) doc.spec_no= string.Empty;
            if (doc.Stock== null) doc.Stock= string.Empty;
            if(doc.RefundFrom == null) doc.RefundFrom = string.Empty;

            if (doc.DocId ==0)
            {
                doc.IsChecked = 0;

            }

            return base.Save(doc, user, out err);

        }

        public override void SaveItems(RefundRegist doc, DateTime time)
        {
            ////删除旧的
            //DB.FSql.Update<RefundRegistImage>()
            //    .Where(a => a.Isdel == false && a.DocId == doc.DocId)
            //    .Set(a => a.Isdel, true)
            //    .ExecuteAffrows();

            //foreach (var item in doc.ImageUrls)
            //{
            //    item.DocId = doc.DocId;
            //    item.Isdel = false;
            //    //item.OccurDate = doc.OccurDate;
            //}


            //DB.FSql.InsertOrUpdate<RefundRegistImage>()
            //    .SetSource(doc.ImageUrls)
            //    //.IgnoreColumns(nameof(RefundRegist.ch))
            //    .ExecuteAffrows();

        }

        public List<RefundRegistImage> GetItems(RefundRegist doc)
        {
            return DB.FSql.Select<RefundRegistImage>()
                .Where(a => a.Isdel == false && a.DocId == doc.DocId)
                .ToList()
                .OrderBy(a => a.ItemId)
                .ToList();
        }

        public async Task<List<RefundRegistImage>> GetImagesUlrs(int id)
        {
            return (await  DB.FSql.Select<RefundRegistImage>()
                .Where(a => a.Isdel == false && a.DocId == id)
                .ToListAsync())
                .OrderBy(a => a.ItemId)
                .ToList();
        }

        public async Task DeleteItem(RefundRegistImage item)
        {
            await DB.FSql.Update<RefundRegistImage>()
                .Where(a => a.id == item.id)
                .Set(a => a.Isdel, true)
                .ExecuteAffrowsAsync();

        }





        public async Task<IEnumerable<dynamic>> QueryList(RefundRegQueryDto pr)
        {
            var begin = pr.Begin.Date;
            var end= pr.End.LastTimeOfDay();

            var list = await DB.FSql.Select<RefundRegist, StockWechat>()
                .LeftJoin((a, b) => a.Stock == b.Stock && b.isdel == false)
                .Where((a, b) => a.Isdel == false)
                .Where((a, b) => a.OccurDate >= begin && a.OccurDate <= end)
                .WhereIf(pr.IsSendMessage != null, (a, b) => a.IsSendMessage == pr.IsSendMessage)
                .WhereIf(!string.IsNullOrEmpty(pr.Shop), (a,b) => a.Shop== pr.Shop) 
                .WhereIf(!string.IsNullOrEmpty(pr.Stock), (a,b) => a.Stock== pr.Stock)
                .WhereIf(!string.IsNullOrEmpty(pr.src_tids), (a,b) => a.src_tids== pr.src_tids)
                .WhereIf(!string.IsNullOrEmpty(pr.platform_goods_id), (a,b) => a.platform_goods_id== pr.platform_goods_id)
                .ToListAsync((a, b) => new
                {
                    a.DocId,
                    a.Number,
                    a.OccurDate,
                    a.Stock,
                    a.spec_no,
                    a.platform_goods_id,
                    a.IsChecked,
                    a.IsSendMessage,
                    a.LogiNo,
                    a.RefundQty,
                    a.trade_no,
                    a.Remarks,
                    //a.src_tids,
                    a.Processor,
                    //a.Shop,
                    a.PayAmount,
                    a.Reason,
                    a.Reason2,
                    a.Reason3,
                    a.RefundFrom,
                    a.PreparedBy,
                    b.WechatGroup,
                });

            return list.Select(a => new
            {
                a.DocId,
                选择= false,
                编号 = a.Number,
                制单人 = a.PreparedBy,
                日期 = a.OccurDate,
                处理人 = a.Processor,
                //店铺 = a.Shop,
                订单编号 = a.trade_no,
                货品编号 = a.platform_goods_id,

                //商家编码 = a.spec_no,
                快递单号 = a.LogiNo,
                退货数量= a.RefundQty,
                金额 = a.PayAmount,
                仓库 = a.Stock,
                详细赔偿原因 = a.Reason,
                赔偿原因2= a.Reason2,
                赔偿原因3 = a.Reason3,
                赔偿来源 = a.RefundFrom,
                备注 = a.Remarks,
                是否已发送消息= a.IsSendMessage,
                微信群= a.WechatGroup,
            })
                .ToList();
                
        }



        public async Task SaveImages(IEnumerable<RefundRegistImage> items)
        {
            if (items == null)
            {
                return;
            }

            //await DB.FSql.InsertOrUpdate<RefundRegistImage>()
            //    .SetSource(items)
            //    .ExecuteAffrowsAsync();

            var newlist = items.Where(a=> a.id<=0).ToList();    
            foreach (var item in newlist)
            {
                var id = await DB.FSql.Insert(item).ExecuteIdentityAsync();
                item.id = (int)id;
            }

            var oldList = items.Where(a=> a.id> 0).ToList();    
            await DB.FSql.Update<RefundRegistImage>()
                .SetSource(oldList)
                .ExecuteAffrowsAsync();
        }


        /// <summary> 提取订单信息 </summary>
        public async Task<IEnumerable<tradeItem>> Pickup(string find, string trade_no = null)
        {
            if(string.IsNullOrEmpty(find) && string.IsNullOrEmpty(trade_no))
            {
                return new List<tradeItem>();   
            }

            var list = await DB.FSql.Select<RefundDoc, RefundDocItem>()
                .InnerJoin((a,b) => a.RefundNo == b.RefundNo && a.Batch== b.Batch)
                .Where((a,b) => a.isdel== false)
                .WhereIf(!string.IsNullOrEmpty(find), (a,b) => a.logistics_no == find)
                .WhereIf(!string.IsNullOrEmpty(trade_no), (a,b) => a.trade_no == trade_no)
                .WithLock(SqlServerLock.NoLock)
                .ToListAsync((a,b)=> new tradeItem
                {
                    id=a.Id,
                    trade_no=a.trade_no,
                    src_tids=a.trade_no,
                    logistics_name=a.logistics_name,
                    logistics_no=a.logistics_no,
                    warehouse=a.Stock,
                    //goods_name= b.goodsName,
                    //spec_name=b.specName,   
                    num=a.RefundQty,
                    platform_goods_id = b.goods_no,
                    refund_status= a.RefundReason,
                });

            
            return list;
            
        }


        public void SetSendStatus(int id, bool isSended)
        {
            if(id>0)
            {
                DB.FSql.Update<RefundRegist>()
                    .Where(a=> a.DocId == id && a.Isdel== false )
                    .Set(a=> a.IsSendMessage == isSended)
                    //.ExecuteAffrowsAsync();
                    .ExecuteAffrows();
            }
        }

        public async Task<Result> DeleteItems(List<int> list)
        {
            if(list?.Any() != true)
            {
                return new Result(true);
            }


            var time = await DB.FSql.GetTimeAsync();

            foreach (var item in list)
            {
                await DB.FSql.Update<RefundRegist>()
                    .Where(a => a.DocId == item)
                    .Set(a => a.Isdel, true)
                    .Set(a => a.IsdelDate, time)
                    .ExecuteAffrowsAsync();

                await DB.FSql.Update<RefundRegistImage>()
                    .Where(a => a.DocId == item)
                    .Set(a => a.Isdel, true)
                    .ExecuteAffrowsAsync();
            }

            return new Result(true);

        }
    }





}



 
